﻿/*
Copyright 2011 Shane Ng

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Linq;
using System.Text;
using freemarker.template;
using System.Collections.Generic;
using System.Reflection;

namespace Freemarker.Net {
    public class NetObjectModel : StringModel, TemplateModel, TemplateHashModel {
        Dictionary<string, PropertyInfo> props = new Dictionary<string, PropertyInfo>();
        Dictionary<string, MethodModel> methods = new Dictionary<string, MethodModel>();
        Dictionary<string, ExtensionMethodModel> extensionMethods = new Dictionary<string, ExtensionMethodModel>();

        public NetObjectModel(object data, NetObjectWrapper wrapper): base(data, wrapper){
            var type = data.GetType();
            foreach (var p in type.GetProperties()) {
                props.Add(p.Name, p);
            }
            foreach (var m in type.GetMethods()) {
                if (!methods.ContainsKey(m.Name)) {
                    methods.Add(m.Name, new MethodModel(data, wrapper, m.Name));
                }
            }
        }

        public virtual TemplateModel get(string key) {
            if (props.ContainsKey(key)) {
                return wrapper.wrap(props[key].GetGetMethod().Invoke(data, null));
            }
            else if (methods.ContainsKey(key)) {
                return methods[key];
            }
            else if (wrapper.ExtensionTypes.Count > 0) {
                if (!extensionMethods.ContainsKey(key)) {
                    extensionMethods[key] = new ExtensionMethodModel(data, wrapper, key);
                }
                return extensionMethods[key];
            }
            else {
                return TemplateModel.__Fields.NOTHING;
            }            
        }

        public virtual bool isEmpty() {
            return props.Count == 0;
        }
    }
}
